<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 11/13/18
 * Time: 4:27 PM
 */

namespace caroltc\jenkinsapp\util;

/**
 * fallbacks
 */
class FileCache
{
    function __call($name, $args)
    {
        if($name=='set')
        {
            switch(count($args))
            {
                case 0:break;
                case 1: break;
                case 2: $this->setComm($args[0], $args[1]); break;
                case 4: $this->setLimit($args[0], $args[1],$args[2],$args[3]); break;
                default: //do something
                    break;
            }
        }
    }

    function setComm($key, $value)
    {
        if($key){
            $data = json_decode($this->get_file(DIR_ROOT ."filecache.php"),true);
            if(!$value){
                unset($data["$key"]);
            }else{
                $item = array();
                $item["$key"] = $value;
                $item['expire_time'] = 0;
                $item['create_time'] = time();
                $data["$key"] = $item;
            }
            $this->set_file("filecache.php",json_encode($data));
        }
    }

    function setLimit($key, $value,$tag,$time)
    {
        if($key){
            $data = json_decode($this->get_file(DIR_ROOT ."filecache.php"),true);
            if(!$value){
                unset($data["$key"]);
            }else{
                $item = array();
                $item["$key"] = $value;
                $item['expire_time'] = $time;
                $item['create_time'] = time();
                $data["$key"] = $item;
            }

            $this->set_file("filecache.php",json_encode($data));
        }
    }

    function get($key)
    {
        if($key){
            $data = json_decode($this->get_file(DIR_ROOT ."filecache.php"),true);
            if($data&&array_key_exists($key,$data)){
                $item = $data["$key"];
                if(!$item){
                    return false;
                }
                if($item['expire_time']>0&&$item['expire_time'] < time()){
                    return false;
                }

                return $item["$key"];
            }else{
                return false;
            }

        }
    }

    function get_file($filename) {
        if (!file_exists($filename)) {
            $fp = fopen($filename, "w");
            fwrite($fp, "<?php exit();?>" . '');
            fclose($fp);
            return false;
        }else{
            $content = trim(substr(file_get_contents($filename), 15));
        }
        return $content;
    }

    function set_file($filename, $content) {
        $fp = fopen($filename, "w");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }
}